<template>
  <div class="resume_header">
    <span>账号设置</span>
  </div>
  <div class="resume_center" style="">
    <div class="account_info" v-if="true">
      <p style="height: 40px;align-items: center;display: flex;margin-bottom: 10px;">账号信息</p>
      <div class="account_card">
        <div class="card_left">
          <span style="color: #999;width: 130px;">手机号
          </span>
          <span>{{ phone ? `+86 ${phone}` : '您尚未绑定手机号，请绑定' }}</span>
        </div>
        <el-button type="primary" @click="handleChange('phone')">修改</el-button>
      </div>
      <div class="account_card">
        <div class="card_left">
          <span style="color: #999;width: 130px;">邮箱
          </span>
          <span>{{ email ? ` ${email}` : '您尚未绑定邮箱，请绑定' }}</span>
        </div>
        <el-button type="primary" @click="handleChange('email')">修改</el-button>
      </div>
      <div class="account_card">
        <div class="card_left">
          <span style="color: #999;width: 130px;">密码
          </span>
          <span>{{ pwd }}</span>
        </div>
        <el-button type="primary" @click="handleChange('pwd')">修改</el-button>
      </div>
    </div>
  </div>
  <!-- 身份校验 -->
  <el-dialog v-model="vPwdDialog" title="身份校验" modal destroy-on-close>
    <el-form ref="vPwdForm" :model="form" :rules="loginRules">
      <el-form-item label="账号" :label-width="formLabelWidth">
        <el-input v-model="form.email" autocomplete="off" readonly />
      </el-form-item>
      <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
        <el-input v-model="form.password" autocomplete="off" type="password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="vPwdDialog = false">取消</el-button>
        <el-button type="success" @click="handle(vPwdForm)">提交</el-button>
      </span>
    </template>
  </el-dialog>


  <!-- pwd -->
  <el-dialog v-model="upPwdDialog" title="修改密码" modal :open-delay="500" destroy-on-close>
    <el-form ref="upPwdForm" :model="pwdVerify" :rules="pwdVerifyRules">
      <el-form-item label="请输入新密码" :label-width="formLabelWidth" prop="password_1">
        <el-input v-model="pwdVerify.password_1" autocomplete="off" type="password" />
      </el-form-item>
      <el-form-item label="请再次输入新密码" :label-width="formLabelWidth" prop="password_2">
        <el-input v-model="pwdVerify.password_2" autocomplete="off" type="password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="upPwdDialog = false">取消</el-button>
        <el-button type="success" @click="upPwd(upPwdForm)">提交</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- phone -->
  <el-dialog v-model="upPhoneDialog" title="更换手机" modal :open-delay="500" destroy-on-close>
    <el-form ref="upPhoneForm" :model="phoneVerify" :rules="PhoneVerifyRules">
      <el-form-item label="请输入手机号" :label-width="formLabelWidth" prop="phone">
        <el-input v-model="phoneVerify.phone" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="upPhoneDialog = false">取消</el-button>
        <el-button type="success" @click="upPhone(upPhoneForm)">提交</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- email -->
  <el-dialog v-model="upEmailDialog" title="更换邮箱" modal :open-delay="500" destroy-on-close>
    <el-form ref="upEmailForm" :model="emailVerify" :rules="emailVerifyRules">
      <el-form-item label="请输入邮箱" :label-width="formLabelWidth" prop="email">
        <el-input v-model="emailVerify.email" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="upEmailDialog = false">取消</el-button>
        <el-button type="success" @click="upEmail(upEmailForm)">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang='ts'>

import { reactive, ref, onMounted, computed, onBeforeMount, watch } from "vue"
import { useStore } from "vuex";
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'
import { VAccountpwd, elmessage, data } from "@/hook/hook"
import { upUserPwd, vUserPwd, upUserEmail, upUserPhone } from "@/api/userApi"
import { loginOu } from "@/api/authApi"
import type { FormInstance, FormRules } from 'element-plus'
// 第一个表单是校验邮箱和密码，所以就用登录的表单校验方式
import { loginUser, loginRules } from "@/utills/loginValidators";
import { pwdVerify, pwdVerifyRules, emailVerify, emailVerifyRules, phoneVerify, PhoneVerifyRules } from "@/utills/accountSetValidators";

import { Phone } from "@element-plus/icons-vue";
export default {
  name: 'UserBasicInfo',
  components: {

  },
  setup() {
    const router = useRouter()
    const upPwdForm = ref<FormInstance>()
    const upPhoneForm = ref<FormInstance>()
    const upEmailForm = ref<FormInstance>()
    const vPwdForm = ref<FormInstance>()

    const store = useStore()
    const changPwdDialog1 = ref(false)
    const vPwdDialog = ref(false)
    const upPwdDialog = ref(false)
    const upEmailDialog = ref(false)
    const upPhoneDialog = ref(false)
    const formLabelWidth = '140px'
    // 用户基本信息
    const userAccount = store.state.userState.userBasicInfo
    const accountInfos = {
      phone: computed(() => userAccount.phone),
      email: computed(() => userAccount.email),
      pwd: "为了您的账号安全，建议您定期修改密码",
    }
    const form = reactive({
      email: computed(() => store.state.userState.userBasicInfo.email),
      password: "",
      changeType: ""
    })

    // 打开第一个对话框
    const handleChange = async (changeType: string) => {
      vPwdDialog.value = true
      if (changeType == "pwd") {
        form.changeType = "pwd"

      }
      if (changeType == "email") {
        form.changeType = "email"
      }
      if (changeType == "phone") {
        form.changeType = "phone"
      }
    }
    // 打开第二个对话框
    const handle = async (formEl: FormInstance | undefined) => {
      // vPwdDialog.value=false
      if (!formEl) return
      // formEl.resetFields()
      await formEl.validate((valid, fields) => {
        if (valid) {
          const newData = {
            ...data(),
            password: form.password

          }
          vUserPwd(newData).then((res: any) => {
            if (res.data["code"] == "200") {
              vPwdDialog.value = false
              formEl.resetFields()
              if (form.changeType == "pwd") {
                // 打开第二个对话框
                upPwdDialog.value = true
              }
              if (form.changeType == "phone") {

                upPhoneDialog.value = true
              }
              if (form.changeType == "email") {

                upEmailDialog.value = true

              }


            } else {

              elmessage(res.data["message"], res.data["type"])
            }
          })
        }
      })
    }

    const upEmail = async (formEl: FormInstance | undefined) => {
      if (!formEl) return
      // formEl.resetFields()
      await formEl.validate(async (valid, fields) => {
        if (valid) {

          // console.log("新密码：", pwdVerify);
          const newData = {
            ...data(),
            email: emailVerify.email,
          }
          await upUserEmail(newData).then((res: any) => {
            if (res.data["code"] == "200") {
              store.commit("upUserEmail", emailVerify.email)
              elmessage(res.data["message"], res.data["type"])
              // 关闭对话框
              upEmailDialog.value = false
            } else if (res.data["code"] == "301") {
              elmessage(res.data["message"], res.data["type"])
            }
            else {
              // 关闭对话框
              upEmailDialog.value = false
              console.log(res.data["message"]);
            }
          })

          formEl.resetFields()

        }
      })
    }
    const upPhone = async (formEl: FormInstance | undefined) => {
      if (!formEl) return
      // formEl.resetFields()
      await formEl.validate(async (valid, fields) => {
        if (valid) {
          const newData = {
            ...data(),
            phone: phoneVerify.phone,
          }
          await upUserPhone(newData).then((res: any) => {
            if (res.data["code"] == "200") {

              store.commit("upUserPhone", phoneVerify.phone)
              elmessage(res.data["message"], res.data["type"])
              // 关闭对话框
              upPhoneDialog.value = false

            } else if (res.data["code"] == "301") {
              elmessage(res.data["message"], res.data["type"])
            }
            else {
              // 关闭对话框
              upPhoneDialog.value = false
              console.log(res.data["message"]);
            }
          })

          formEl.resetFields()
        }
      })
    }
    const upPwd = async (formEl: FormInstance | undefined) => {
      if (!formEl) return
      // formEl.resetFields()
      await formEl.validate((valid, fields) => {
        if (valid) {

          const newData = {
            ...data(),
            password: pwdVerify.password_1,
          }
          upUserPwd(newData).then((res: any) => {
            if (res.data["code"] == "200") {
              elmessage(res.data["message"], res.data["type"])
              loginOu(data())
              store.commit("loginOut")
              setTimeout(() => {
                router.replace("/login")
              }, 500);
              localStorage.clear()

            } else {
              console.log(res.data["message"]);

            }


          })
          // 关闭对话框
          upPwdDialog.value = false
          formEl.resetFields()

        }
      })
    }


    return {

      ...accountInfos,
      changPwdDialog1,
      vPwdDialog,
      upPwdDialog, upEmailDialog, upPhoneDialog,
      formLabelWidth,
      form,
      vPwdForm,
      upPwdForm, upPhoneForm, upEmailForm,

      pwdVerify, pwdVerifyRules, emailVerify, emailVerifyRules, phoneVerify, PhoneVerifyRules,

      upPwd, upPhone, upEmail,
      handleChange,
      handle,

      loginRules,


    }


  }
}
</script>
<style scoped>
.el-input {
  width: 300px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

.account_card {
  display: inline-flex;
  height: 30px;
  align-items: center;
  font-size: 16px;
  width: 600px;
  justify-content: space-between;
  padding-left: 20px;

  margin-bottom: 15px;
}

.card_left {
  /* height: 30px; */
  margin-top: 20px;
  margin-bottom: 20px;
  display: inline-flex;

  /* align-items: center; */
}






.account_info {
  padding-left: 40px;
  padding-top: 10px;
  height: calc(100% - 10px);
  font-size: 18px;
  /* position: relative; */
  /* height: 600px; */
  /* background-color: #FFF; */
}

.account_info:hover {
  transition-duration: 0.3s;
  transition-property: box-shadow;
  box-shadow: 0 0 3px #97999b;
  cursor: pointer;
}



.resume_center {
  font-family: '微软雅黑';
  height: 500px;
  background-color: #FFF;
}

.resume_header {
  background-color: rgb(215, 215, 215);
  height: 50px;
  display: flex;
  align-items: center;
  padding-left: 20px;

}
</style>